import {Injectable} from '@angular/core';
import {TpHttpService} from './tp-http.service';
import {TpStorageService} from './tp-storage.service';
import {ArrayUtils} from '../utils/array-utils';

@Injectable({
    providedIn: 'root'
})
export class DocFocusService {
    constructor(private httpService: TpHttpService,
                private tpStorageService: TpStorageService) {
    }

    /**
     * 关注文档
     * @param {string} docId 文档ID
     */
    focus(docId: string) {
        this.httpService.get(`/api/user/${docId}/focus`).subscribe(result => {
            console.log(`关注${docId}成功！`);
        });
    }

    /**
     * 取消关注
     * @param {string} docId 文档ID
     */
    unfocus(docId: string) {
        this.httpService.del(`/api/user/${docId}/focus`).subscribe(result => {
            console.log(`取消关注${docId}成功！`);
        });
    }

    /**
     * 与本地的关注进行合并
     * @param {string[]} focusDocIds
     */
    mergeFocusDocs(focusDocIds: string[]): void {
        const currentDocIds: string[] = this.tpStorageService.getObj(TpStorageService.KEY_MY_FOCUS);
        const newFocusDocs: string[] = [];
        if (currentDocIds) {
            currentDocIds.forEach(id => {
                const index = ArrayUtils.indexOf(focusDocIds, id);
                if (index > -1) {
                    return;
                }
                focusDocIds.push(id);
                newFocusDocs.push(id);
            });
        }
        this.tpStorageService.set(TpStorageService.KEY_MY_FOCUS, JSON.stringify(focusDocIds));
        if (newFocusDocs) {
            newFocusDocs.forEach(docId => {
                this.focus(docId);
            });
        }
    }

    getFocusDocIds(): string[] {
        const topDocIdStr = this.tpStorageService.getObj(TpStorageService.KEY_MY_FOCUS);
        if (topDocIdStr) {
            return topDocIdStr;
        }
        this.tpStorageService.set(TpStorageService.KEY_MY_FOCUS, '[]');
        return [];
    }
}
